package com.ccp.dev.workflow.service.bpm;

import com.ccp.dev.core.basic.engine.GroovyScriptEngine;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.workflow.bpmconst.BpmConst;
import com.ccp.dev.workflow.model.BpmNodeScript;
import com.ccp.dev.workflow.service.BpmNodeScriptService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * ClassDescribe:
 * 脚本任务用于执行groovy脚本
 *
 * @author :wangcheng
 * Date: 2019-08-05
 */
@Service
public class ScriptTask implements JavaDelegate {

    private static final Logger Logger = LoggerFactory.getLogger(GroovyScriptEngine .class);

    @Override
    public void execute(DelegateExecution execution) {
        String processDefinitionId = execution.getProcessDefinitionId();
        String nodeId = execution.getCurrentActivityId();

        BpmNodeScriptService bpmNodeScriptService = (BpmNodeScriptService) AppUtil.getBean("bpmNodeScriptService");

        // 获取脚本节点的脚本对象
        BpmNodeScript nodeScript = bpmNodeScriptService.getScriptByType(nodeId, processDefinitionId, BpmConst.ScriptNodeScript);

        if (BeanUtils.isEmpty(nodeScript)) {
            return;
        }

        String script = nodeScript.getScript();

        if (StringUtil.isEmpty(script)) {
            return;
        }

        GroovyScriptEngine scriptEngine = AppUtil.getBean(GroovyScriptEngine.class);
        Map<String, Object> variables = execution.getVariables();
        variables.put("execution", execution);
        scriptEngine.execute(script, variables);

        Logger.debug("execution script: " + script);
    }
}
